    export default {
        name: "zsmb",
        setup(props, { emit }) {
            const { smartSpeak } = inject('speech'); //语音
            const tableData = ref([]);
            const total = ref(0);
            const pagesys = ref({page: 1, pageSize: 15, search: ''});
            const xmlist = ref([]);
            
            onMounted(async() => {
                await getbgsxlist();
                await getData();
            });
            
            const getData = async () => {
				const res = await getpictemplist(pagesys.value);
				tableData.value = res.items;
				total.value = res.total;
			};
			
			//获取项目列表
			const getbgsxlist = async () => {
			    const res = await getbgsxlistapi({page: 1, pageSize: 100});
				if(res.total > 0){
					xmlist.value = [];
					res.items.forEach(item=>{
						xmlist.value.push({label: item.formname, value: item.id, fields: item.fields});
					})
					sessionStorage.setItem('xmlist', JSON.stringify(xmlist.value));
				}
			};
			
			//获取项目名
			const getname = (id) => {
			    if(!id) return '';
			    let xm = xmlist.value.find(item => String(item.value) === String(id));
			    return xm ? xm.label : '';
			}
            
            //每页条数改变时触发 选择一页显示多少行
            const handleSizeChange = (val) => {
                pagesys.value.page = 1;
                pagesys.value.pageSize = val;
                getData();
            };
        
            //翻页
            const handleCurrentChange = (val) => {
                pagesys.value.page = val;
                getData();
            };
        
            //每页数量改变
            const sizechange = (e) => {
                pagesys.value.pageSize = e;
                getData();
            };
        	
            //新建模板
        	const addzsmbform = () => {
        	    let row = {name: '', xmid: '', backgroundurl: '', fields: []};
                sessionStorage.setItem('currentTemplate', JSON.stringify(row));
        	    router.push({ name: 'AdminAddZsmb', query: { id: null } });
        	};
        	
        	//修改模板
        	const editzsmbform = (row) => {
        	    if(!row.id) return;
        	    sessionStorage.setItem('currentTemplate', JSON.stringify(row));
        	    router.push({ name: 'AdminAddZsmb', query: { id: row.id } });
        	};
        	
        	//删除模板
        	const handleDelete = _.debounce(async (row) => {
        	    if(!row.id) return ElMessage.error('数据不存在');
                try {
                    smartSpeak('您确定要删除这个模板吗');
                    await ElMessageBox.confirm(' 您确定要删除这个模板吗？', '删除确认', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }); 
                    await delzsmbapi({ id: row.id });
                    getData();;
                } catch (error) {
                    if (error === 'cancel') {
                        return;  // 用户点击了取消，不进行处理
                    }
                    console.error(' 删除失败:', error);
                    smartSpeak('删除失败，请稍后再试');
                    ElMessage.error(' 删除失败，请稍后再试');
                }
        	}, 300);
            
            // 预览模板
            const handleView = (row) => {
               if (!row.backgroundurl || !row.xmid) {
                    smartSpeak('请先上传背景图并选择项目');
                    ElMessage.warning('请先上传背景图并选择项目');
                    return;
                }
                var canvasSize = {width: 0, height: 0};
                const img = new Image()
                img.src = row.backgroundurl
                img.onload = () => {
                    canvasSize.width = img.naturalWidth
                    canvasSize.height = img.naturalHeight
                    const previewData = {
                        background: row.backgroundurl,
                        fields: row.fields,
                        width: canvasSize.width,
                        height: canvasSize.height
                    };
                    let xm = xmlist.value.find(item => String(item.value) === String(row.xmid));
                    let xmfields = xm ? xm.fields : null;
                    const previewWindow = window.open('', '_blank');
                    previewWindow.document.write(`
                        <!DOCTYPE html>
                        <html>
                        <body style="margin:0">
                            <div style="position:relative;width:${previewData.width}px;height:${previewData.height}px">
                                <img src="${previewData.background}" style="position:absolute"/>
                                ${previewData.fields.map(f => {
                                    // 关键修改：通过映射表获取字体栈
                                    const fontFamily = systemFontMap[f.fontfamily] || systemFontMap.default;
                                    console.log(fontFamily);
                                    return `
                                        <div style="
                                            position:absolute;
                                            left:${f.x}px;
                                            top:${f.y}px;
                                            color:${f.fontcolor || '#000'};
                                            font-size:${f.fontsize || 14}px;
                                            font-family:${fontFamily};
                                            white-space: nowrap;
                                            overflow: hidden;
                                            text-overflow: ellipsis;
                                        ">
                                            ${xmfields ? xmfields[f.name].name : f.name}
                                        </div>
                                    `;
                                }).join('')}
                            </div>
                        </body>
                        </html>
                    `);
                }
                img.onerror = () => {
                    ElMessage.error('背景图加载失败')
                    canvasSize.width = 800
                    canvasSize.height = 600
                }
            }
            
            return {
                getname,
                xmlist,
                handleView,
                handleDelete,
                tableData,
                getData,
                total,
                addzsmbform,
                pagesys,
                handleSizeChange,
                handleCurrentChange,
                sizechange,
                editzsmbform,
            };
        },
        
        template: `
            <div>
                <div style="display: flex; align-items: center;">
                    <el-button type="primary" @click="addzsmbform()">新建模板</el-button>
                    <el-input style="width:500px;margin-left: 10px;" v-model="pagesys.search" placeholder="输入关键词查找模板" clearable @keyup.enter="getData" @clear="getData">
                        <template #prefix>
                        	<el-icon class="el-input__icon"><search /></el-icon>
                        </template>
    					<template #append>
                            <el-button @click="getData">搜索</el-button>
                        </template>
    				</el-input>
                </div>
            
                <el-table :data="tableData" table-layout="auto" :header-cell-style="{'font-size': '14px', background: '#f9f9f9'}" border show-overflow-tooltip :row-key="(row) => row.id" v-if="total > 0" class="mt-1">
                    <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
                    <el-table-column prop="id" width="100" label="ID" align="center"></el-table-column>
                    <el-table-column prop="name" label="模板名称">
                        <template #default="scope">
                            <span>{{scope.row.name}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="xmid" label="关联查询项目">
                        <template #default="scope">
                            <span v-if="scope.row.xmid">{{ getname(scope.row.xmid) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="endtime" label="背景图" :width="170">
                        <template #default="scope">
                            <el-image v-if="scope.row.backgroundurl" :src="scope.row.backgroundurl" style="height:60px;" :preview-src-list="[scope.row.backgroundurl]" fit="cover">
        						<template #error>
        							<div class="image-error">图片加载失败</div>
        						</template>
        					</el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="CreatedAt" label="创建时间" :width="200">
                        <template #default="scope">
                            <span>{{ $validators.formatDate(scope.row.CreatedAt)}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" :width="180">
                        <template #default="scope">
                            <el-button link type="success" @click="handleView(scope.row)">预览</el-button>
                            <el-button link type="primary" @click="editzsmbform(scope.row)">修改</el-button>
                            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            	<el-pagination v-if="tableData.length > 0" background @size-change="sizechange" :page-sizes="[10, 20, 30, 50]" :page-size="pagesys.pageSize" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" :total="total" :current-page.sync="pagesys.page"></el-pagination>
            </div>
        `
    }